package com.jichangxiu.framework.filter;

import cn.hutool.core.collection.ListUtil;
import com.jichangxiu.common.entity.bo.XssRequestWrapper;
import com.jichangxiu.common.properties.JcxProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * XssFilter:
 *
 * @author Jcx
 * @create 2023-04-04 13:09
 */
@Slf4j
@AllArgsConstructor
public class XssFilter extends OncePerRequestFilter {

    private JcxProperties jcxProperties;

    private final PathMatcher pathMatcher;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new XssRequestWrapper(request), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 放行不过滤的URL
        ArrayList<String> urls = ListUtil.toList(jcxProperties.getSecurityProperties().getXssExcludeUrls().split(","));
        return urls.stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getRequestURI()));
    }

}
